window.onload = function(){
    let keyword = GetRequest().keyword.replace("+", " ");
    let searchText = document.querySelector("#search-text");
    let resultBxo = document.querySelector("#search-result");
    searchText.value = keyword;
    search(searchText, resultBxo);
}

function search(input, resultContent) {
    fetch("/search.json").then(res => res.json()).then(data => {
        if(!input) return;
        input.addEventListener('input', ev => {
            var str = '<ul class=\"list-unstyled post-list mb-5 post-list\">';
            var keywords = ev.target.value.trim().toLowerCase().split(/[\s\-]+/);
            resultContent.innerHTML = '';
            if(ev.target.value.trim().length <= 0) return;
            data.forEach(item => {
                var isMath = false;
                keywords.forEach(key => {
                    if(!isMath && item.title.trim().toLowerCase().includes(key)){
                        isMath = true;
                    }
                })

                if(isMath){
                    str += `<li class="py-4"><h3><a class="fs-4" href="${item.url}">${item.title}</a></h3></li>`
                }
                
            })
            str += '</ul>';
            resultContent.innerHTML = str;
        })

        input.dispatchEvent(new Event('input'));
    });
    
}

function GetRequest() {
    var url = location.search; 
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substring(1),
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
} 